<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="80%">
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px" v-loading="formLoading">
      <el-row :gutter="20">

        <el-col :span="6">
          <el-form-item label="库存状态" prop="inventoryStatus">
            <el-select v-model="formData.inventoryStatus" placeholder="请选择库存状态">
              <el-option v-for="dict in getStrDictOptions(DICT_TYPE.MOLD_INVENTORY_STATUS)" :key="dict.value"
                :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="模具名" prop="name">
            <el-input v-model="formData.name" placeholder="请输入模具名" :disabled="formType === 'update'" />
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="编码" prop="code">
            <el-input v-model="formData.code" placeholder="请输入编码" :disabled="formType === 'update'" />
          </el-form-item>
        </el-col>


        <el-col :span="6">
          <el-form-item label="图号" prop="drawingNoId">
            <el-select v-model="formData.drawingNoId" filterable clearable placeholder="请选择图号" style="width: 100%;"
              @change="handleDrawingNoChange">
              <el-option v-for="drawingNo in drawingNoList" :key="drawingNo.id" :label="drawingNo.drawingNo"
                :value="drawingNo.id" />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="模具类型" prop="deptId">
            <el-tree-select v-model="moldCategory" :data="categoryTree" :props="defaultProps" check-strictly filterable
              clearable default-expand-all placeholder="请选择模具类型" value-key="id" />
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="客户" prop="customer">
            <el-input v-model="formData.customer" placeholder="客户" />
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="部门" prop="deptId">
            <el-tree-select v-model="formData.deptId" :data="deptTree" :props="defaultProps" check-strictly filterable
              clearable default-expand-all placeholder="请选择部门" value-key="id" />
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="绑定设备" prop="devId">
            <el-select :loading="remortLoading" remote :remote-method="remoteSearch" clearable filterable
              v-model="formData.devId" placeholder="请输入至少3个字符搜索设备">
              <el-option v-for="dict in EquipmentList" :key="dict.id"
                :label="`${dict.equipmentName} - ${dict.code} - ${dict.installPosition}`" :value="dict.id" />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="模腔数" prop="totalCavity">
            <el-row :gutter="10">
              <el-col :span="12">
                <el-input v-model.number="formData.totalCavity" placeholder="总模腔数" type="number" />
              </el-col>
              <el-col :span="12">
                <el-input v-model.number="formData.availableCavity" placeholder="可用模腔数" type="number" />
              </el-col>
            </el-row>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="寿命" prop="totalUsageCount">
            <el-row :gutter="10">
              <el-col :span="12">
                <el-input v-model.number="formData.totalUsageCount" placeholder="寿命" type="number" />
              </el-col>
              <el-col :span="12">
                <el-input v-model.number="formData.usedCount" placeholder="已使用" type="number" />
              </el-col>
            </el-row>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="预警/延期" prop="warningCount">
            <el-row :gutter="10">
              <el-col :span="12">
                <el-input v-model.number="formData.warningCount" placeholder="预警次数" type="number" />
              </el-col>
              <el-col :span="12">
                <el-input v-model.number="formData.delayCount" placeholder="延期次数" type="number" />
              </el-col>
            </el-row>
          </el-form-item>
        </el-col>

        <!--         <el-col :span="6">
          <el-form-item label="预警次数" prop="warningCount">
            <el-input v-model="formData.warningCount" placeholder="请输入预警次数" />
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="延期次数" prop="delayCount">
            <el-input v-model="formData.delayCount" placeholder="请输入延期次数" />
          </el-form-item>
        </el-col> -->
      </el-row>


      <el-form-item label="仓库/储位" required>
        <el-row :gutter="10" style="width: 100%">
          <el-col :span="5">
            <el-select v-model="formData.warehouseId" filterable clearable @change="handleWarehouseChange"
              placeholder="请选择仓库">
              <el-option v-for="warehouse in warehouseList" :key="warehouse.id"
                :label="`${warehouse.code} - ${warehouse.name}`" :value="warehouse.id" />
            </el-select>
          </el-col>
          <el-col :span="5">
            <el-select v-model="formData.storageId" filterable clearable placeholder="请选择储位">
              <el-option v-for="storage in filteredStorageList" :key="storage.id"
                :label="`${storage.code} - ${storage.name}`" :value="storage.id" />
            </el-select>
          </el-col>
        </el-row>
      </el-form-item>

      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="bom类型" prop="bomCategoryId">
            <el-select v-model="formData.bomCategoryId" placeholder="请选择bom类型" :disabled="formType === 'update'">
              <el-option v-for="dict in getStrDictOptions(DICT_TYPE.MOLD_BOM_CATEGORY)" :key="dict.value"
                :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="工步" prop="oprationStep">
            <el-input v-model="formData.oprationStep" placeholder="请输入工步" type="number"
              :disabled="formType === 'update'" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="数量" prop="quantity">
            <el-input v-model.number="formData.quantity" placeholder="请输入数量" type="number"
              :disabled="formType === 'update'" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="保养类型" prop="upkeepId">
            <el-select v-model="formData.upkeepId" filterable clearable placeholder="请选择保养类型" style="width: 100%;"
              @change="handleUpkeepChange">
              <el-option v-for="upkeepcategory in upkeepList" :key="upkeepcategory.id" :label="upkeepcategory.name"
                :value="upkeepcategory.id" />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="核算方式" prop="upkeepCycleCategory">
            <el-select v-model="upkeepCycleCategory" placeholder="核算方式" clearable class="!w-240px" disabled>
              <el-option v-for="dict in getIntDictOptions(DICT_TYPE.MOLD_UPKEEP_CATEGORY_ACCOUNT_METHOD)"
                :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="保养周期" prop="upkeepCycle">
            <el-select v-model="upkeepCycle" placeholder="请选择保养周期" disabled>
              <el-option label="请选择字典生成" value="" />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="提醒周期" prop="remindCycle">
            <el-select v-model="remindCycle" placeholder="提醒周期" disabled>
              <el-option label="请选择字典生成" value="" />
            </el-select>
          </el-form-item>
        </el-col>

      </el-row>

      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="上次保养日期" prop="lastUpkeepTime">
            <el-date-picker v-model="formData.lastUpkeepTime" type="date" value-format="x" placeholder="选择上次保养日期" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="下次保养日期" prop="nextUpkeepTime">
            <el-date-picker v-model="formData.nextUpkeepTime" type="date" value-format="x" placeholder="选择下次保养日期" />
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="保养人" prop="upkeeperId">
            <el-select v-model="formData.upkeeperId" filterable clearable placeholder="保养人" style="width: 100%;">
              <el-option v-for="user in userList" :key="user.id" :label="user.nickname" :value="user.id" />
            </el-select>
          </el-form-item>
        </el-col>

        <!--         <el-col :span="6">
          <el-form-item label="保养日期" prop="upkeepTime">
            <el-date-picker v-model="formData.upkeepTime" type="date" value-format="x" placeholder="选择保养日期" />
          </el-form-item>
        </el-col> -->
      </el-row>

      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="复检类型" prop="recheckId">
            <el-select v-model="formData.recheckId" filterable clearable placeholder="请选择复检类型" style="width: 100%;"
              @change="handleRecheckChange">
              <el-option v-for="recheck in recheckList" :key="recheck.id" :label="recheck.name" :value="recheck.id" />
            </el-select>
          </el-form-item>
        </el-col>

        <!-- 在复检类型组件后面添加 -->
        <el-col :span="6">
          <el-form-item label="复检周期" prop="recheckCycle">
            <el-input v-model="recheckCycle" placeholder="复检周期" disabled />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="上次复检日期" prop="lastRecheckTime">
            <el-date-picker v-model="formData.lastRecheckTime" type="date" value-format="x" placeholder="选择上次复检日期" />
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="下次复检日期" prop="nextRecheckTime">
            <el-date-picker v-model="formData.nextRecheckTime" type="date" value-format="x" placeholder="选择下次复检日期" />
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="复检人" prop="recheckerId">
            <el-select v-model="formData.recheckerId" filterable clearable placeholder="复检人" style="width: 100%;">
              <el-option v-for="user in userList" :key="user.id" :label="user.nickname" :value="user.id" />
            </el-select>
          </el-form-item>
        </el-col>

        <!--  <el-col :span="6">
          <el-form-item label="复检日期" prop="recheckTime">
            <el-date-picker v-model="formData.recheckTime" type="date" value-format="x" placeholder="选择复检日期" />
          </el-form-item>
        </el-col> -->

      </el-row>

      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="领用人" prop="borrowerId">
            <el-select v-model="formData.borrowerId" filterable clearable placeholder="领用人" style="width: 100%;">
              <el-option v-for="user in userList" :key="user.id" :label="user.nickname" :value="user.id" />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="领用时间" prop="borrowTime">
            <el-date-picker v-model="formData.borrowTime" type="date" value-format="x" placeholder="选择领用时间" />
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="归还人" prop="returnerId">
            <el-select v-model="formData.returnerId" filterable clearable placeholder="归还人" style="width: 100%;">
              <el-option v-for="user in userList" :key="user.id" :label="user.nickname" :value="user.id" />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="归还时间" prop="returnTime">
            <el-date-picker v-model="formData.returnTime" type="date" value-format="x" placeholder="选择归还时间" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="描述" prop="description">
        <Editor v-model="formData.description" height="150px" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { getIntDictOptions, getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import { UpkeepCategoryApi } from '@/api/mold/upkeepcategory'
import { defaultProps, handleTree } from '@/utils/tree'
import { AccountApi, Account } from '@/api/mold/account'
import { DrawingNoApi, DrawingNo } from '@/api/mold/drawingno'
import { WarehouseApi, Warehouse } from '@/api/mold/warehouse'
import { StorageApi, Storage } from '@/api/mold/storage'
import * as DeptApi from '@/api/system/dept'
import * as UserApi from '@/api/system/user'
import type { UserVO } from '@/api/system/user'
import { EquipmentManageApi, EquipmentManage } from '@/api/business/equipmentmanage'
import { CategoryApi } from '@/api/mold/category'
import { RecheckCategoryApi } from '@/api/mold/recheckcategory'

/** 模具台账 表单 */
defineOptions({ name: 'AccountForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  inventoryStatus: "1",
  name: undefined,
  code: undefined,
  drawingNoId: undefined,
  deptId: undefined,
  devId: undefined,
  totalCavity: undefined,
  availableCavity: undefined,
  totalUsageCount: undefined,
  usedCount: undefined,
  warningCount: undefined,
  delayCount: undefined,
  warehouseId: undefined,
  storageId: undefined,
  bomCategoryId: undefined,
  oprationStep: undefined,
  quantity: 1, // 设置默认值为1
  upkeepId: undefined,
  recheckId: undefined,
  lastUpkeepTime: undefined,
  nextUpkeepTime: undefined,
  upkeeperId: undefined,
  // upkeepTime: undefined,
  lastRecheckTime: undefined,
  nextRecheckTime: undefined,
  recheckerId: undefined,
  //recheckTime: undefined,
  borrowerId: undefined,
  borrowTime: undefined,
  returnerId: undefined,
  returnTime: undefined,
  description: undefined,
  customer: undefined,
})
const formRules = reactive({
  inventoryStatus: [{ required: true, message: '库存状态不能为空', trigger: 'change' }],
  drawingNoId: [{ required: true, message: '图号id不能为空', trigger: 'change' }],
  // totalCavity: [{ required: true, message: '总腔数不能为空', trigger: 'blur' }],
  totalUsageCount: [{ required: true, message: '寿命不能为空', trigger: 'blur' }],
  warningCount: [{ required: true, message: '预警次数不能为空', trigger: 'blur' }],
  name: [{
    required: true,
    validator: (rule: any, value: string, callback: any) => {
      // 判断主模(drawingNoId)、工步(oprationStep)任意一个字段为空的情况下，模具名不能为空
      if ((!formData.value.drawingNoId || !formData.value.oprationStep) && !value) {
        callback(new Error('当主模或工步为空时，模具名不能为空'));
      } else {
        callback();
      }
    },
    trigger: 'blur'
  }],
  code: [{
    required: true,
    validator: (rule: any, value: string, callback: any) => {
      // 判断主模(drawingNoId)、工步(oprationStep)任意一个字段为空的情况下，编码不能为空
      if ((!formData.value.drawingNoId || !formData.value.oprationStep) && !value) {
        callback(new Error('当主模或工步为空时，编码不能为空'));
      } else {
        callback();
      }
    },
    trigger: 'blur'
  }],
  quantity: [{
    required: true,
    validator: (rule: any, value: number, callback: any) => {
      // 校验数量必须大于0
      if (value === undefined || value === null) {
        callback(new Error('数量不能为空'));
      } else if (value <= 0) {
        callback(new Error('数量必须大于0'));
      } else {
        callback();
      }
    },
    trigger: 'blur'
  }],
  lastUpkeepTime: [{ required: true, message: '上次保养日期不能为空', trigger: 'change' }],
  lastRecheckTime: [{ required: true, message: '上次保养日期不能为空', trigger: 'change' }]

})

const formRef = ref() // 表单 Ref

// 新增选中的仓库ID
// 过滤后的储位列表
const filteredStorageList = ref<Storage[]>([])
const categoryTree = ref()
const moldCategory = ref()
const customer = ref()
const drawingNoList = ref()
const deptTree = ref() // 树形结构
const warehouseList = ref<Warehouse[]>([])
const storageList = ref<Storage[]>([])
const upkeepList = ref()
const userList = ref<UserVO[]>([])
const remortLoading = ref(false)
const EquipmentList = ref([])
const upkeepCycleCategory = ref()
const upkeepCycle = ref()
const recheckCycle = ref()
const recheckList = ref()
const remindCycle = ref()


// 监听上次保养日期和保养周期变化，自动计算下次保养日期
watch([() => formData.value.lastUpkeepTime, () => upkeepCycle.value], ([lastTime, cycle]) => {
  if (lastTime && cycle) {
    const nextTime = new Date(lastTime)
    nextTime.setDate(nextTime.getDate() + cycle)
    formData.value.nextUpkeepTime = nextTime.getTime()
  } else {
    formData.value.nextUpkeepTime = undefined
  }
})

// 监听上次复检日期和复检周期变化，自动计算下次复检日期
watch([() => formData.value.lastRecheckTime, () => recheckCycle.value], ([lastTime, cycle]) => {
  if (lastTime && cycle) {
    const nextTime = new Date(lastTime)
    nextTime.setDate(nextTime.getDate() + cycle)
    formData.value.nextRecheckTime = nextTime.getTime()
  } else {
    formData.value.nextRecheckTime = undefined
  }
})


const getUserList = async () => {
  userList.value = await UserApi.getSimpleUserList()
}

/** 获得保养类型树 */
const getUpkeepList = async () => {
  upkeepList.value = []
  const data = await UpkeepCategoryApi.getUpkeepCategoryAll()
  upkeepList.value = handleTree(data)
}

/** 获得复检类型树 */
const getRecheckList = async () => {
  recheckList.value = []
  const data = await RecheckCategoryApi.getRecheckCategoryAll()
  recheckList.value = handleTree(data)
}


/** 获得模具类型树 */
const getCategoryTree = async () => {
  categoryTree.value = []
  const data = await CategoryApi.getCategoryAll()
  categoryTree.value = handleTree(data)
}


/** 获得模具图号列表 */
const getDrawingNoList = async () => {
  drawingNoList.value = []
  const data = await DrawingNoApi.getDrawingNoAll()
  console.log('drawingNoList.value', drawingNoList)
  drawingNoList.value = handleTree(data)
}

/** 获得部门树 */
const getDeptTree = async () => {
  deptTree.value = []
  let parentId = 115
  const data = await DeptApi.getDeptsById(parentId)
  let dept: Tree = { id: parentId, name: '阿能集团', children: [] }
  dept.children = handleTree(data)
  deptTree.value.push(dept)
}

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  warehouseList.value = await WarehouseApi.getWarehouses()
  storageList.value = await StorageApi.getStorageAll()
  getUserList()
  getDrawingNoList()
  getDeptTree()
  getUpkeepList()
  getRecheckList()
  getCategoryTree()
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await AccountApi.getAccount(id)
      // 如果获取到的数据中quantity为空，则设置默认值为1
      if (formData.value.quantity === undefined || formData.value.quantity === null) {
        formData.value.quantity = 1;
      }


      // 如果已有图号ID，设置模具类型和客户
      if (formData.value.drawingNoId) {
        const selectedDrawingNo = drawingNoList.value.find((item: any) => item.id === formData.value.drawingNoId)
        if (selectedDrawingNo) {
          moldCategory.value = selectedDrawingNo.categoryId
          customer.value = selectedDrawingNo.customer
        }
      }

      // ADD: 如果有绑定设备ID，创建一个包含设备信息的对象以在选择器中显示
      if (formData.value.devId && formData.value.devName) {
        // 创建一个临时对象以显示设备信息
        const deviceInfo = {
          id: formData.value.devId,
          equipmentName: formData.value.devName,
          code: formData.value.devCode,
          installPosition: formData.value.devPosition
        };

        // 将设备信息添加到设备列表中（如果尚不存在）
        if (!EquipmentList.value.some(item => item.id === deviceInfo.id)) {
          EquipmentList.value.push(deviceInfo);
        }
      }

      // ADD: 如果有保养类型ID，加载保养类型详情
      if (formData.value.upkeepId) {
        await handleUpkeepChange(formData.value.upkeepId)
      }

      // ADD: 如果有复检类型ID，加载复检类型详情
      if (formData.value.recheckId) {
        await handleRecheckChange(formData.value.recheckId)
      }

    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗




// 添加图号选择变化处理函数
const handleDrawingNoChange = (drawingNoId: number) => {
  if (drawingNoId) {
    const selectedDrawingNo = drawingNoList.value.find((item: any) => item.id === drawingNoId)
    if (selectedDrawingNo) {
      moldCategory.value = selectedDrawingNo.categoryId
      formData.value.customer = selectedDrawingNo.customer
      // 自动设置仓库和储位
      if (selectedDrawingNo.warehouseId) {
        formData.value.warehouseId = selectedDrawingNo.warehouseId
        // 触发仓库选择变化以更新储位列表
        handleWarehouseChange(selectedDrawingNo.warehouseId, true)
      }
      if (selectedDrawingNo.storageId) {
        formData.value.storageId = selectedDrawingNo.storageId
      }
      // 自动设置保养类型
      if (selectedDrawingNo.upkeepId) {
        formData.value.upkeepId = selectedDrawingNo.upkeepId
        handleUpkeepChange(selectedDrawingNo.upkeepId)
      }
      if (selectedDrawingNo.recheckId) {
        formData.value.recheckId = selectedDrawingNo.recheckId
        handleRecheckChange(selectedDrawingNo.recheckId)
      }
    }
  } else {
    moldCategory.value = undefined
    customer.value = undefined
    formData.value.warehouseId = undefined
    formData.value.storageId = undefined
    formData.value.upkeepId = undefined
    formData.value.recheckId = undefined

    // 清空保养相关字段
    upkeepCycleCategory.value = undefined
    upkeepCycle.value = undefined
    remindCycle.value = undefined

    // 清空复检周期
    recheckCycle.value = undefined
  }
}
// 处理仓库选择变化
const handleWarehouseChange = (warehouseId: number, isEdit = false) => {
  if (warehouseId) {
    filteredStorageList.value = storageList.value.filter(storage => storage.warehouseId === warehouseId)
  } else {
    filteredStorageList.value = []
  }
  // 只有在非编辑状态下才清除已选择的储位
  if (!isEdit) {
    formData.value.storageId = undefined
  }
}



/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()

  // 打印bomCategoryId的值用于调试
  //console.log('bomCategoryId value:', formData.value.bomCategoryId)


  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as Account
    if (formType.value === 'create') {
      await AccountApi.createAccount(data)
      message.success(t('common.createSuccess'))
    } else {
      await AccountApi.updateAccount(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    inventoryStatus: "1",
    name: undefined,
    code: undefined,
    drawingNoId: undefined,
    deptId: undefined,
    devId: undefined,
    totalCavity: undefined,
    availableCavity: undefined,
    totalUsageCount: undefined,
    usedCount: undefined,
    warningCount: undefined,
    delayCount: undefined,
    warehouseId: undefined,
    storageId: undefined,
    bomCategoryId: undefined,
    oprationStep: undefined,
    quantity: 1, // 设置默认值为1
    upkeepId: undefined,
    recheckId: undefined,
    lastUpkeepTime: undefined,
    nextUpkeepTime: undefined,
    upkeeperId: undefined,
    // upkeepTime: undefined,
    lastRecheckTime: undefined,
    nextRecheckTime: undefined,
    recheckerId: undefined,
    // recheckTime: undefined,
    borrowerId: undefined,
    borrowTime: undefined,
    returnerId: undefined,
    returnTime: undefined,
    description: undefined,
    customer: undefined, // 添加这一行
  }
  // 显式重置模具类型和客户字段
  moldCategory.value = undefined
  customer.value = undefined

  // 重置保养相关字段
  upkeepCycleCategory.value = undefined
  upkeepCycle.value = undefined
  remindCycle.value = undefined
  recheckCycle.value = undefined


  formRef.value?.resetFields()
}


const remoteSearch = async (query) => {
  // 修改为超过2个字符才执行搜索
  if (query && query.length > 2) {
    remortLoading.value = true
    let params = {
      keyWords: query
    }
    EquipmentList.value = await EquipmentManageApi.getEquipmentManageList(params)
    remortLoading.value = false
  } else {
    // 如果查询关键字为空或长度不足，清空结果列表
    EquipmentList.value = []
  }
}


// 添加保养类型选择变化处理函数
const handleUpkeepChange = async (upkeepId: number) => {
  if (upkeepId) {
    try {
      // 调用API获取保养类型详情
      const upkeepDetail = await UpkeepCategoryApi.getUpkeepCategory(upkeepId)
      if (upkeepDetail) {
        // 填充保养周期类型、保养周期和提醒周期
        upkeepCycleCategory.value = upkeepDetail.accountMethod
        upkeepCycle.value = upkeepDetail.upkeepPeriod
        remindCycle.value = upkeepDetail.reminderPeriod
      }

    } catch (error) {
      console.error('获取保养类型详情失败:', error)
    }
  } else {
    // 清空相关字段
    /*     upkeepCycleCategory.value = undefined
        upkeepCycle.value = undefined
        remindCycle.value = undefined */
    formData.value.nextUpkeepTime = undefined
  }
}

// 修改 handleRecheckChange 函数
const handleRecheckChange = async (recheckId: number) => {
  if (recheckId) {
    try {
      // 调用API获取复检类型详情
      const recheckDetail = await RecheckCategoryApi.getRecheckCategory(recheckId)
      if (recheckDetail) {
        // 填充复检周期
        recheckCycle.value = recheckDetail.recheckPeriod

        // 如果上次复检日期已存在，自动计算下次复检日期
        if (formData.value.lastRecheckTime && recheckDetail.recheckPeriod) {
          const nextTime = new Date(formData.value.lastRecheckTime)
          nextTime.setDate(nextTime.getDate() + recheckDetail.recheckPeriod)
          formData.value.nextRecheckTime = nextTime.getTime()
        }
      }
    } catch (error) {
      console.error('获取复检类型详情失败:', error)
    }
  } else {
    // 清空复检周期和下次复检日期
    recheckCycle.value = undefined
    formData.value.nextRecheckTime = undefined
  }
}

</script>